﻿using MyCode.Project.Domain.Config;
using MyCode.Project.Infrastructure.Cache;
using MyCode.Project.Infrastructure.Common;
using MyCode.Project.Infrastructure.Constant;
using MyCode.Project.Infrastructure.UnityExtensions;
using System;
using System.IO;
using System.Text;
using System.Web;

namespace MyCode.Project.WebApi.App_Modules
{
    public class WebApiModule : IHttpModule
    {
        /// <summary>
        /// 您将需要在网站的 Web.config 文件中配置此模块
        /// 并向 IIS 注册它，然后才能使用它。有关详细信息，
        /// 请参见下面的链接: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpModule Members

        public static IMyCodeCacheService _myCodeCacheService = null;
        public void Dispose()
        {
            //此处放置清除代码。
        }

        public void Init(HttpApplication context)
        {
            //var sree = context.Response;
            // 下面是如何处理 LogRequest 事件并为其 
            // 提供自定义日志记录实现的示例       
            context.BeginRequest += (new
                 EventHandler(this.Application_BeginRequest));
          

        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        public void OnLogRequest(Object source, EventArgs e)
        {
            //可以在此处放置自定义日志记录逻辑
        }

        private void Application_BeginRequest(Object source, EventArgs e)
        {
            HttpApplication Application = (HttpApplication)source;
            HttpContext ctx = Application.Context;
            if(_myCodeCacheService==null)
                _myCodeCacheService = UnityHelper.GetService<IMyCodeCacheService>();
            //IP地址
            string isIp = ctx.Request.UserHostAddress;
            string url = ctx.Request.RawUrl;
            string requestDataStr = "";
            var stream = ctx.Request.InputStream;
            if (stream != null && stream.Length > 0)
            {
                stream.Position = 0; //当你读取完之后必须把stream的读取位置设为开始
                StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
                requestDataStr = reader.ReadToEnd().ToString();
                if (reader.EndOfStream)
                    stream.Position = 0;
            }
            if (!string.IsNullOrWhiteSpace(url) && url.Length > 3 && url.Contains("api/"))
            {
                var sb = new StringBuilder(Environment.NewLine + "-----------------------------------------" + Environment.NewLine);
                sb.AppendLine(DateTime.Now + "  " + url);
                sb.AppendLine($"请求IP:{isIp}");
                sb.AppendLine($"请求参数:{requestDataStr}");             
                try
                {
                    sb.AppendLine($"请求token:{ctx.Request.Headers["Authorization"]}");                   
                    var logininfo = TokenHelper.Get(ctx.Request.Headers["Authorization"].Trim(),
                      SystemConfig.JwtKey,
                      Const.LoginInfoKey);

                    Log(sb.ToString());
                    if(logininfo!=null)
                        Log(JsonHelper.ToJson(logininfo));
                }
                catch (Exception ex)
                {
                    Log("异常的访问:"+sb.ToString());                   
                }
            }
        }

        private void Application_EndRequest(Object source, EventArgs e)
        {

        }

        public static void Log(string str)
        {
            string now = DateTime.Now.Date.ToString("yyyy-MM-dd");
            string path = HttpContext.Current.Server.MapPath("~") + @"/RequestLog/";
            string fileName = now + "Log.txt";
            string sourceFilePath = path + fileName;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            try
            {
                using (StreamWriter sw = File.AppendText(sourceFilePath))
                {

                    if (!System.IO.File.Exists(sourceFilePath))
                    {
                        FileInfo fileinfo = new FileInfo(sourceFilePath);
                        fileinfo.Create();
                    }
                    sw.WriteLine(str);
                }
            }
            catch
            { }
        }


    }
}